package com.boot.modules.profile.service.impl;

import cn.hutool.core.date.DateUtil;
import com.boot.common.constant.GlobalVar;
import com.boot.common.constant.MessageConstant;
import com.boot.common.property.UploadProperties;
import com.boot.common.result.Result;
import com.boot.modules.profile.service.ProfileService;
import com.boot.system.entity.SysUser;
import com.boot.system.mapper.UserMapper;
import com.boot.system.service.UserCacheService;
import com.boot.util.SecurityUtil;
import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import jodd.io.FileUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@RequiredArgsConstructor
@Service("profileService")
public class ProfileServiceImpl extends ServiceImpl<UserMapper, SysUser> implements ProfileService {

    private final UserCacheService userCacheService;

    private final UploadProperties uploadProperties;

    @Override
    public SysUser findByUsername(String username) {
        return this.mapper.selectByUsername(username);
    }

    @Override
    public SysUser findByEmail(String email) {
        return this.mapper.selectByEmail(email);
    }

    @Override
    public SysUser findByPhone(String phone) {
        return this.mapper.selectByPhone(phone);
    }

    @Override
    public boolean register(SysUser user) {
        return super.save(user);
    }

    @Override
    public SysUser getLoginUserInfo() {
        SysUser user = userCacheService.getCacheUser(SecurityUtil.getUsername());
        if (user != null) {
            //移除敏感字段
            user.setPassword(null);
        }
        return user;
    }

    @Override
    public Result<?> uploadAvatar(MultipartFile file) {
        if (file.isEmpty()) {
            return Result.error(MessageConstant.UPLOAD_FILE_EMPTY);
        }
        try {
            String timeDir = DateUtil.today();
            String filePath = uploadProperties.getAvatarPath() + File.separator + timeDir;
            // 创建目录
            FileUtil.mkdir(filePath);
            // 保存文件
            String fileName = GlobalVar.systemTime + "-" + file.getOriginalFilename();
            FileUtil.writeBytes(filePath + File.separator + fileName, file.getBytes());
            // 保存头像
            QueryWrapper query = QueryWrapper.create().from(SysUser.class);
            query.eq(SysUser::getId, SecurityUtil.getUid());
            this.update(new SysUser().setAvatar("/avatars/" + timeDir + "/" + fileName), query);
            // 更新缓存
            userCacheService.updateCacheUser(SecurityUtil.getUid());
            // 返回结果
            Map<String, String> map = new HashMap<>();
            map.put("fileName", file.getOriginalFilename());
            map.put("filePath", "/avatars/" + timeDir + "/" + fileName);
            return Result.success(map);
        } catch (Exception e) {
            log.error("上传头像失败", e);
            return Result.error(MessageConstant.UPLOAD_FILE_ERROR);
        }
    }

}
